using System;
using System.Collections;
using System.Collections.Generic;

namespace Miao
{
    /// <summary>
    /// 协程组.
    /// 提供对协程的统一管理
    /// 协程封装类，批量独立维护一个集体协程
    /// </summary>
    public class CoroutineGroup
    {
        private readonly List<RunningCoroutine> runningCoroutines = new List<RunningCoroutine>();


        /// <summary>
        /// 当前协程组全部运行完毕调用。
        /// </summary>
        public event Action OnCompleteGroup;

        /// <summary>
        /// 停止所有在当前协程组下运行的协程
        /// </summary>
        public void Stop()
        {
            foreach (var runningCoroutine in runningCoroutines) CoroutineStarter.RemoveInternal(runningCoroutine.coroutineInternal);
            runningCoroutines.Clear();
        }
        /// <summary>
        /// 在当前协程组下启动一个协程,封装类
        /// </summary>
        /// <param name="enumerator"></param>
        /// <returns></returns>
        public RunningCoroutine Start(IEnumerator enumerator)
        {
            RunningCoroutine runningCoroutine = CoroutineStarter.Start(enumerator);
            runningCoroutine.onStop += () => runningCoroutines.Remove(runningCoroutine);
            runningCoroutines.Add(runningCoroutine);
            runningCoroutine.onComplete += CompleteGroup;
            return runningCoroutine;
        }

        internal void CompleteGroup()
        {
            if(runningCoroutines.Count==0)
            {
                OnCompleteGroup?.Invoke();
            }
        }
    }
}